package com.lz.frame.config.security.controller;

import java.util.*;
import com.google.gson.Gson;
import com.lz.frame.annotation.AnonymousAccess;
import com.lz.frame.common.R;
import com.lz.frame.config.security.DO.LoginDTO;
import com.lz.frame.config.security.MyUserDetails02;
import com.lz.frame.domain.service.UserLoginService;
import com.lz.frame.filter.JwtUtil;
import com.xinchili.mysqlSimulateRedis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@AnonymousAccess
@RestController
@RequestMapping("/sys/security")
public class LoginController {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private Gson gson;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录逻辑
     * 生成两个token
     * access_token
     * refresh_token:存放在redis中
     *
     */

    @RequestMapping("/login")
    public R login(@RequestBody LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 加载用户信息
        // 使用这个（类的）方法调用吗？
        MyUserDetails02 userDetails = (MyUserDetails02) userDetailsService.loadUserByUsername(username);
        System.out.println("userDetails:" + userDetails.getPassword());
        System.out.println("password:" + password);
        // 验证密码（需要注入PasswordEncoder）
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            return R.error("密码错误");
        }
        String accessToken = jwtUtil.generateAccessToken(userDetails);
        //根据用户信息创建

        String json = gson.toJson(userDetails);
        String refreshToken = UUID.randomUUID().toString();
        // 生成access_token和refresh_token
        redisService.set("refresh_token:" + refreshToken, json, 60 * 60 * 1000);
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", accessToken);
        map.put("refresh_token", refreshToken);
        return R.success(map);
    }

    /**
     * 注册逻辑
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    public R register(String username, String password) {
        boolean register = userLoginService.register(username, password);
        return register ? R.success() : R.error("注册失败");
    }

    /**
     * 刷新access_token
     */
    @RequestMapping("/refresh")
    public R refresh(String refreshToken) {
        String json = redisService.get("refresh_token:" + refreshToken);
        if (json == null) {
            return R.error("refresh_token已过期");
        }
        MyUserDetails02 userDetails = gson.fromJson(json, MyUserDetails02.class);
//        MyUserDetails02 userDetails = jwtUtil.parseToUser(json);
        String accessToken = jwtUtil.generateAccessToken(userDetails);
        return R.success(accessToken);
    }


}
